/*
 	Keycounter.cpp

 	Copyright (c) 2008 Bojan Rajkovic

 	Permission is hereby granted, free of charge, to any person obtaining a copy
 	of this software and associated documentation files (the "Software"), to deal
		in the Software without restriction, including without limitation the rights
 	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 	copies of the Software, and to permit persons to whom the Software is
 	furnished to do so, subject to the following conditions:
	
 	The above copyright notice and this permission notice shall be included in
 	all copies or substantial portions of the Software.

 	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 	THE SOFTWARE.
*/

#include "../include/Keycounter.h"

Keycounter::Keycounter() {
	Keycounter::Keycounter(strdup(DEFAULT_INPUT_DEVICE), strdup(DEFAULT_OUTPUT_FILE));
}

Keycounter::Keycounter(std::string EventDevice, std::string OutputFile) {
	Open(EventDevice, OutputFile);
}

void Keycounter::Open(std::string EventDevice, std::string OutputFile) {
	this->eventReader.open(EventDevice.c_str());
	this->outputWriter.open(OutputFile.c_str(), ios::trunc);

	if(!this->eventReader.good()) {
		throw KeycounterException(Utility::FormatString(_("Failed to open event device %s, make sure the daemon is running as root."), EventDevice.c_str()));
	}
	
	if (!this->outputWriter.good()) {
		throw KeycounterException(Utility::FormatString(_("Failed to open output file %s, make sure the daemon is running as root."), OutputFile.c_str()));
	}
	
	this->startupTime = time(NULL);
	
	Utility::LogMessage("Created keycounter.", M_INFO);
}

bool Keycounter::Pulse() {
	if (Pulse::DoPulse(this->keys)) {
		this->keys = 0;
		this->lastPulse = time(NULL);
		return true;
	} else return false;
}

void Keycounter::Run() {
		Utility::LogMessage("Started keycounter.", M_INFO);
        while (1) {
                // Read the struct from the event device reader
                struct input_event inputEvent;
                Config configuration;
				configuration.readFile(strdup(DEFAULT_CONFIG_FILE));
                this->eventReader.read(reinterpret_cast<char*>(&inputEvent), sizeof(struct input_event));
                // If there was a keystroke
                if (inputEvent.value == 1) {
                        this->keys++; // increment the count of keys since last pulse
                        this->sessionKeys++; // increment the count of keys for this session
                
                        // Write everything out to the output file
                        // First, we gotta rewind the output stream
                        this->outputWriter.seekp(0, ios_base::beg);
                       
                        if (static_cast<bool>(configuration.lookup("application.keycounter.verbose"))) {
                                // Okay, let's put everything out to pastue
                                outputWriter << Utility::FormatString(_("%li total keys pressed since keycounter was started up on %s,"
                                	"%f minutes ago."), this->sessionKeys, Utility::FormatTime(this->startupTime).c_str(), 
                                	ProgramUptime()) << endl;
                                outputWriter << Utility::FormatString(_("%li total keys pressed since the last pulse on %s, "
                                	"%f minutes ago."), this->keys, Utility::FormatTime(this->lastPulse).c_str(), 
                                	TimeSinceLastPulse()) << endl;
                                outputWriter << Utility::FormatString(_("This is an average of %f keys per minute since the"
                                	" keycounter started."), this->sessionKeys/ProgramUptime()) << endl;
                                outputWriter << Utility::FormatString(_("This is an average of %f keys per minute since the "
                                	"system started, session_keys/uptime, %f minutes ago"), 
                                	this->sessionKeys/SystemUptime(), SystemUptime()) << endl;
                        } else {
	                        outputWriter << Utility::FormatString("%li|%li|%f|%f|%f|%i", this->keys, this->sessionKeys, 
								ProgramUptime(), this->keys/ProgramUptime(), this->keys/SystemUptime(), 
								static_cast<int>(this->lastPulse)) << endl;
                        }
                }
        }
}





